package common

import (
	"com.haojuetrace/actualCombat/model"
	"github.com/golang-jwt/jwt"
	"time"
)

/*
	使用jwt生成token与解析token
*/

var jwtket = []byte("haojuetrace")

type Claims struct {
	UserId int
	jwt.StandardClaims
}

//RegisterToken 生成token
func RegisterToken(user *model.Users) (tokenString string, err error) {
	expirationTime := time.Now().Add(30 * time.Minute) //token过期时间
	claims := &Claims{
		UserId: user.Id, //用户id 用于后续查库检测用户是否存在
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(), //token发行时间
			Issuer:    "haojuetrace.com", //token发行人
			Subject:   "user token",      //token主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) //创建token
	tokenString, err = token.SignedString(jwtket)
	if err != nil {
		return "", err
	}
	return tokenString, nil

}

//ParseToken 解析token
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { //解析token
		return jwtket, nil
	})
	if err != nil {
		return nil, nil, err
	}
	return token, claims, nil
}
